package com.xywy.common.sync;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Handler;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xywy.common.bean.BloodPresureDataFromServer;
import com.xywy.common.util.MD5Util;
import com.xywy.fwc.net.BaseParser;
import com.xywy.fwc.net.DataCallBack;
import com.xywy.fwc.net.Request;
import com.xywy.me.bean.User;
import com.xywy.me.bean.UserKeeper;
import com.xywy.wjk.bean.BloodPressureData;
import com.xywy.wjk.dao.BloodPressureDataDao;
import com.xywy.wjk.dao.BloodPressureDataDao.Properties;
import com.xywy.wjk.observer.ObserverConstants;

import de.greenrobot.dao.query.QueryBuilder;

/**
 * 血压计数据同步方法；
 * 
 * @author yangyu
 * 
 */
public class SyncBloodPresureDevice implements ISyncBleDevice {
	private Context mContext;
	private BloodPressureDataDao bloodPressureDataDao;
	private SharedPreferences sp;
	private Editor editor;
//	private String userid = "";
	private User current_user;

	public SyncBloodPresureDevice(Context context,
			BloodPressureDataDao bloodPressureDataDao) {
		this.mContext = context;
		this.bloodPressureDataDao = bloodPressureDataDao;
		sp = mContext.getSharedPreferences("config", Context.MODE_PRIVATE);
		editor = sp.edit();
//		userid = sp.getString("userid", "");
		current_user = UserKeeper.getCurrentUser(mContext);
	}

	@Override
	public List getUnuploadData() {
		long lastSaveTime = sp.getLong(current_user.getUserid()+"last_download_blood_presure_time", 1000); // 最后的上传时间
		QueryBuilder<BloodPressureData> qb = bloodPressureDataDao
				.queryBuilder();
		qb.where(Properties.User_id.eq(current_user.getUserid()));
		qb.orderAsc(Properties.Date).where(Properties.Date.gt(lastSaveTime));
		Log.d(TAG, "血压： 从本地获取需要上传的数据: " + qb.list().size());
		return qb.list();
	}

	@Override
	public void syncDataFormServer() {
		long lastDownLoadTime = sp.getLong("last_download_blood_presure_time",
				1000); // 最后的下载时间；
		String device_id = "temp_automactily_device_identify";
		String appCount = "xywy_tizhong";
		String dataType = "xueya";
		String time = (lastDownLoadTime / 1000) + "";
		String maxItem = "200";
		String curPage = "1";
		String sn = "";
		try {
			sn = MD5Util.md5(SECRETKEY_WEIGHT_SCALEF + device_id + dataType
					+ current_user.getUserid() + time + maxItem + curPage + appCount);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String urlStr = "http://api.yun.xywy.com/index.php/api/getdata/data/"
				+ device_id + "/" + appCount + "/" + dataType + "/" + current_user.getUserid()
				+ "/" + time + "/" + maxItem + "/" + curPage + "/" + sn + "/";

		Request.requestData(new BaseParser<List<BloodPresureDataFromServer>>() {
			// 这个地方我需要从服务器获取到的接口返回的key值才能解析
			@Override
			public List<BloodPresureDataFromServer> parseJson(String result) {
//				Log.d(TAG, "血压：解析从服务器上获取数据 ");
				try {
					JSONObject jsonObject = new JSONObject(result);
					int status = jsonObject.getInt("status");
					if (status == 0) { // 正确与服务器交互；
						List<BloodPresureDataFromServer> datas = new ArrayList<BloodPresureDataFromServer>();
						JSONArray array = jsonObject.optJSONArray("data");
						for(int i=0;i<array.length();i++){
							JSONObject item = (JSONObject) array.get(i);
							BloodPresureDataFromServer bs = new BloodPresureDataFromServer();
							bs.setXywy_userid(item.optString("xywy_userid"));
							bs.setApp_user_id(item.optString("app_user_id"));
							bs.setDatatime(Long.parseLong(item.optString("datatime")));
							bs.setHigh(Float.parseFloat(item.optString("high")));
							
							
							bs.setHigh(Float.parseFloat(item.optString("high")));
							bs.setLow(Float.parseFloat(item.optString("low")));
							bs.setHeart(Float.parseFloat(item.optString("heart")));
							bs.setApp_data(item.optString("app_data"));
							bs.setShou_data(item.optString("high"));
							datas.add(bs);
							
						}
						Log.d(TAG, "血压：成功获取数据 ");
						return datas;
					}else {
						return null;
					}
				} catch (JSONException e) {
					e.printStackTrace();
					return null;
				}

			}
		}, new DataCallBack<List<BloodPresureDataFromServer>>() {

			@Override
			public void dataCall(List<BloodPresureDataFromServer> lists) {

				// 3 当数据正常处理之后 ， 开始上传1中获取到的数据；
				if (lists == null) {
					Log.d(TAG, "血压： 当前数据获取失败，或者解析异常， 导致同步体重数据库失败！");
					return;
				}else if (lists.size() == 0) {
					Log.d(TAG, "血压：服务器上面一条都没拉取下来~~");
					uploadDataInRAM(getUnuploadData());
					return;
				}
//				editor.putBoolean("isBind", true).commit();
				for (BloodPresureDataFromServer list : lists) {
					long date = (long) (list.getDatatime() * 1000); // *1000
																	// 因为服务器上为ios
					if(!dataCanInsert(date)){
						continue;
					}
					BloodPressureData data = new BloodPressureData(null, list
							.getHeart(), list.getHigh(), list.getLow(),current_user.getUserid(),
							"State", "temp_automactily_device_identify",
							"temp_handly_device_identify", date);
					bloodPressureDataDao.insert(data);
				}
				mContext.getContentResolver().notifyChange(ObserverConstants.BLOOD_DB_CHANGE, null);
				// 将数据保存之后，获取最后一条的时间来替换本地数据；
				editor.putLong(
						current_user.getUserid()+"last_download_blood_presure_time",
						(long) (lists.get(lists.size() - 1).getDatatime() * 1000))
						.commit();
				uploadDataInRAM(getUnuploadData());

			}

		}, urlStr);
	}
	/**
	 * 
	 * @return
	 */
	
	private boolean dataCanInsert(long time) {
		QueryBuilder<BloodPressureData> qb = bloodPressureDataDao.queryBuilder();
		qb.where(Properties.Date.gt(time-1000));
		qb.where(Properties.Date.gt(time+1000));
		List<BloodPressureData> list = qb.list();
		if(list != null && list.size() >0){
			return false;
		}
       return true;
	}

	@Override
	public void uploadDataInRAM(List<?> baseDatas) {
		final List<BloodPressureData> datas = (List<BloodPressureData>) baseDatas;
		if (datas == null || datas.size() < 1) {
			Log.d("血压", "没有从数据库中获取到血压数据，不需要执行上传方法 。节省流量");
			return;
		}
		/* 循环更改当前的time时间 ，避免上传中之后与ios数据不统一 */
//		List<BloodPressureData> list = new ArrayList<BloodPressureData>();
//		for (BloodPressureData data : datas) {
//			long date = data.getDate();
//			BloodPressureData dataTemp  = data.clone();
//			dataTemp.setDate(date);
//			list.add(dataTemp);
//		}

		HashMap<Object, Object> params = new HashMap<Object, Object>();
		params.put("app_username", "xywy_tizhong");
		String userid = sp.getString("userid", "");
		params.put("xywy_userid", userid);
		params.put("sort", "xueya");
		// -------------------
		String dataStr = turn2ServerJsonData(datas, userid);
		params.put("data", dataStr);
		System.out.println("上传血压的数据----"+dataStr);
		// -------------------
		String sn = SECRETKEY_WEIGHT_SCALEF + userid + "xueya" + dataStr
				+ "xywy_tizhong";
		try {
			params.put("sn", MD5Util.md5(sn));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		Request.postData(new BaseParser() {

			@Override
			public Object parseJson(String result) {
				try {
					JSONObject jsonObject = new JSONObject(result);
					int status = jsonObject.getInt("status");
					if (status == 0) {
						Log.d(TAG, "血压：本地数据上传成功 ");
						sp.edit()
								.putLong("last_download_blood_presure_time",
										datas.get(datas.size() - 1).getDate())
								.commit();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

				return null;
			}

		}, new DataCallBack<String>() {

			@Override
			public void dataCall(String str) {
				System.out.println("上传本次记录的返回值" + str);

			}
		}, "http://api.yun.xywy.com/index.php/api/setdata/data_all/", params);
	}

	/**
	 * 将数据库中提取出来的数据转换成服务器的been
	 * 
	 * @param data
	 */
	private String turn2ServerJsonData(List<BloodPressureData> datas,
			String userID) {
		Gson gson = new Gson();
		List<BloodPresureDataFromServer> jsons = new ArrayList<BloodPresureDataFromServer>();
		for (BloodPressureData data : datas) {
			BloodPresureDataFromServer dataFormServer = new BloodPresureDataFromServer();
			dataFormServer.setApp_data(data.getDevice_id());
			dataFormServer.setApp_user_id("");
			dataFormServer.setDatatime(data.getDate()/1000);// 时间上面已经处理
			dataFormServer.setHeart(data.getHeartRate());
			dataFormServer.setHigh(data.getHighPressure());
			dataFormServer.setLow(data.getLowPressure());
			dataFormServer.setShou_data(data.getHand_str());
			dataFormServer.setXywy_userid(userID);
			jsons.add(dataFormServer);
		}

		return gson.toJson(jsons);
	}
}
